package com.weichen.studentgameexchange.game.controller;

import cn.hutool.core.io.FileUtil;
import com.weichen.studentgameexchange.common.common.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 功能：文件上传下载
 * 作者：惟尘
 * 日期：2025/1/24 9:39
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";//文件存储的目录

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return Result.error("未上传文件");
        }
        String originalFilename = file.getOriginalFilename();
        //aaa.png
        String mianName = FileUtil.mainName(originalFilename);//aaa
        String extName = FileUtil.extName(originalFilename);//png
        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);        //如果当前文件的父级目录不存在，就创建
        }

        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {                     //如果当前上传的文件名已经存在了，需要重命名文件名
            originalFilename = System.currentTimeMillis() + "_"+ mianName + "." + extName;

        }
        file.transferTo(new File(ROOT_PATH + File.separator + originalFilename));   //存储文件到本地磁盘
        String url = "http://"+ ip +":"+ port +"/file/download/" + originalFilename;
        return Result.success(url);//返回文件的链接，这个链接就是文件的下载地址，这个下载地址是后台提供出来的
    }

    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {

//        response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));//附件下载
        String filePath = ROOT_PATH + File.separator + fileName;
        if (!FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);  //数组是一个字节数组，也就是文件的字节流数组
        outputStream.flush();
        outputStream.close();
    }
}
